package com.gcit.seniorWish.web.core.mybatis;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.gcit.seniorWish.web.core.shiro.ShiroKit;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
* 公共字段自动填充
 * 如 ：createBy，updateBy，delFlag
* @author gaozhichang
* @date 2018-02-06 上午 10:46
*/
public class FieldFillHandler extends MetaObjectHandler {
	@Override
	public void insertFill(MetaObject metaObject) {
		if(metaObject.hasSetter("createBy")){
			Object createBy = getFieldValByName("createBy", metaObject);
			if (createBy == null&&ShiroKit.getUser()!=null) {
				setFieldValByName("createBy", ShiroKit.getUser().getId(), metaObject);
			}
		}
		if(metaObject.hasSetter("createTime")){
			Object createTime = getFieldValByName("createTime", metaObject);
			if (createTime == null) {
				setFieldValByName("createTime",new Date(), metaObject);
			}
		}
		if(metaObject.hasSetter("delFlag")){
			Object delFlag = getFieldValByName("delFlag", metaObject);
			if (delFlag == null&&ShiroKit.getUser()!=null) {
				setFieldValByName("delFlag", 0, metaObject);
			}
		}
		if(metaObject.hasSetter("modifyBy")){
			Object updateBy = getFieldValByName("modifyBy", metaObject);
			if (updateBy == null&&ShiroKit.getUser()!=null) {
				setFieldValByName("modifyBy", ShiroKit.getUser().getId(), metaObject);
			}
		}
		if(metaObject.hasSetter("modifyTime")){
			Object modifyTime = getFieldValByName("modifyTime", metaObject);
			if (modifyTime == null) {
				setFieldValByName("modifyTime",new Date(), metaObject);
			}
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		if(metaObject.hasSetter("modifyBy")){
			Object updateBy = getFieldValByName("modifyBy", metaObject);
			if (updateBy == null&&ShiroKit.getUser()!=null) {
				setFieldValByName("modifyBy", ShiroKit.getUser().getId(), metaObject);
			}
		}
		if(metaObject.hasSetter("modifyTime")){
			Object modifyTime = getFieldValByName("modifyTime", metaObject);
			if (modifyTime == null) {
				setFieldValByName("modifyTime",new Date(), metaObject);
			}
		}
	}
}
